import React, { Component } from 'react';
import CommentList from './CommentList.js';
import CommentInput from './CommentInput';

export default class CommentApp extends Component {
    
    constructor() {
        super()
        this.state = {
            comments: []
        }
    }
    handleSubmitComment(comment){
        console.log('submit',comment)
        if(!comment) return;
        if(!comment.username) return alert('请输入用户名');
        if(!comment.content) return alert('请输入评论内容');
        const comments=this.state.comments;
        comments.push(comment)
      
        this.setState({ comments })
        this._saveComments(comments)
    }
    _loadComments(){
        let comments=localStorage.getItem('comments');
        if(comments){
            comments=JSON.parse(comments)
            this.setState({
                comments: comments
            })
        }
    }
    _saveComments(comments){
        localStorage.setItem('comments',JSON.stringify(comments))
    }
    handleDeleteComment (index) {
        console.log(index)
        const comments = this.state.comments
        comments.splice(index, 1)
        this.setState({ comments })
        this._saveComments(comments)
    }


    componentWillMount() {
        this._loadComments()
    }

    render(){
        // const comments = [
        //     {username: 'Jerry', content: 'Hello'},
        //     {username: 'Tomy', content: 'World'},
        //     {username: 'Lucy', content: 'Good'}
        //   ];
        return (
            <div className="wrapper">
                <CommentInput onSubmit={this.handleSubmitComment.bind(this)}></CommentInput>
                <CommentList onDeleteComment={this.handleDeleteComment.bind(this)} comments={this.state.comments}></CommentList>
            </div>
        )
    }
}